﻿Imports System.Windows.Forms
Imports CefSharp
Imports Sy.UI
Imports Sy.UI.Cef
Imports SyCefBrowser = Sy.UI.CefBrowser
Public Class Frm_Main
    Public Shared Property Instance As Frm_Main
    Private Sub Frm_Main_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Instance = Me
        SyCefBrowser.Init() '只能主线程
        Sy.UI.Form.ShadowForm.RegisterShadowForm(Me,, True)
        With Me
            .Icon = OemIcon
            .Text = OemText
            .WindowState = FormWindowState.Maximized
        End With
        Pic_Close.Left = Instance.Width - Pic_Close.Width
        Dim Task = Sub()
                       InitializeChromium()
                       'Looper.Start()
                   End Sub
        Task.BeginInvoke(Null, Null)
#If debug Then
        ShowDebugButton()
#End If
    End Sub
    Private Sub InitializeChromium()
        'Threading.Thread.Sleep(3000)
        Dim LoadUrl = $"file:///{Sy.Environment.AppPath.Replace("\", "/")}/Config/Load.html"
        ChromeBrowser = New SyCefBrowser(LoadUrl)
        Dim JsObjName = "formProcess" 'window.external=formProcess;
        ChromeBrowser.RegisterJsObject(JsObjName, JsObject.Instance)
        InvokEx(Sub()
                    'ChromeBrowser.BackColor = Color.White
                    Controls.Add(ChromeBrowser)
                    ChromeBrowser.Dock = DockStyle.Fill
                    LoadGif.Hide()
                End Sub)
    End Sub
    Public WithEvents ChromeBrowser As SyCefBrowser
    Private Sub ChromeBrowser_DocumentCompleted(sender As SyCefBrowser, DocumentCompletedEventArgs As DocumentCompletedEventArgs) Handles ChromeBrowser.DocumentCompleted
        Const CheckSuccess = " id=""app"""
        Dim CurUrl As String = sender.Address
        If CurUrl.StartsWith(URL) AndAlso DocumentCompletedEventArgs.HtmlSourceCode.Contains(CheckSuccess) Then
            Pic_Close.Visible = False
            ScriptManager.Instance.SetExecuter(Sub(js)
                                                   If ChromeBrowser.CanExecuteJavascriptInMainFrame Then '可以优化成消息队列
                                                       ChromeBrowser.ExecuteScriptAsync(js)
                                                   Else
                                                       Try
                                                           ChromeBrowser.GetMainFrame?.EvaluateScriptAsync(js)
                                                       Catch ex As Exception
                                                           MsgBox(ex.Message,, "Err#146")
                                                       End Try
                                                   End If
                                               End Sub)
        ElseIf CurUrl.ToLower.StartsWith("file://") Then
            LoginSession = Sy.Text.Encode.Url_Decode(LoginSession)
            Dim CookieManager = ChromeBrowser.GetCookieManager
            CookieManager.DeleteCookies(LoginAddress)
            CookieManager.SetCookie(LoginAddress, New Cookie With {
                .Name = "vue_typescript_admin_access_token",
                .Value = LoginSession
            })
            CookieManager.SetCookie(LoginAddress, New Cookie With {
                .Name = "erp_session",
                .Value = LoginSession
            })
            Dim SessionInfo = $"LoginSession:{LoginSession} Token:{Version}"
            Debug.Print(SessionInfo)
            sender.Load(URL)
        End If
        'DocumentCompletedEventArgs.GetDomHtml
    End Sub
    Private Sub ChromeBrowser_NewWindow(sender As SyCefBrowser, e As Sy.UI.NewWindowEventArgs) Handles ChromeBrowser.NewWindow
        Try
            Process.Start(e.Url)
        Catch ex As Exception
            Sy.UI.Form.MsgBox.Show($"Error:{ex.Message}")
        End Try
    End Sub
    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Btn_ShowDevTools.Click
        ChromeBrowser.ShowDevTools
    End Sub
    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Btn_Reload.Click
        ChromeBrowser.Reload()
    End Sub
    Private Sub Pic_Close_Click(sender As Object, e As EventArgs) Handles Pic_Close.Click
        EndTask.Invoke()
    End Sub
    Public Sub CloseFrm()
        EndTask.Invoke()
    End Sub
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ChromeBrowser.Reload()
    End Sub
    Private Sub Button2_Click_1(sender As Object, e As EventArgs) Handles Button2.Click
        Dim Json = JsObject.Instance.VerifyEmail("")
        'Dim Json = JsObject.Instance.VerifyEmails({"1303628841@qq.com", "2111262978@qq.com"}.ToList())
        Console.WriteLine(Json)
    End Sub
    Friend Function ChangeSize() As Integer
        If WindowState = FormWindowState.Maximized Then
            WindowState = FormWindowState.Normal
        Else
            WindowState = FormWindowState.Maximized
        End If
        Return WindowState
    End Function
    Friend Sub MinSize()
        WindowState = FormWindowState.Minimized
    End Sub
    Friend Sub SetCloseButtonVisible(Visible As Boolean)
        Pic_Close.Visible = Visible
    End Sub
    Private DeegbugCount As Integer

    Private Sub Frm_Main_KeyPress(sender As Object, e As KeyPressEventArgs) Handles MyBase.KeyPress
        If e.KeyChar.Equals("d"c) Then
            DeegbugCount += 1
        ElseIf e.KeyChar.Equals("b"c) Then
            If DeegbugCount >= 5 Then
                ShowDebugButton()
            End If
        Else
            DeegbugCount = 0
        End If
    End Sub
    Friend Sub ShowDebugButton()
        Btn_ShowDevTools.Visible = True
        Btn_Reload.Visible = True
        Btn_Test.Visible = True
    End Sub
End Class